import {
    observable,
    action,
    computed,
    runInAction,
    toJS
} from 'mobx';

import BaseStore from '../BaseStore';
import validationUtil from '@/utils/validation';
import {
    noticeMessage
} from '@utils/common-message';

class Store extends BaseStore {

    @observable roleName;
    @observable currentList;

    @observable editRoleId;
    @observable editRoleName;
    @observable editRoleDescription;
    @observable templateTree;
    @observable checkedTreeNodes;
    defaultMenus;
    // 打开弹框的类型
    //     1 -- 新增
    //     2 -- 编辑
    @observable openModal;

    @observable errMsg = {
        editRoleName: '',
        editRoleDescription: '',
    };

    isEditSuccess;
    globalErrMsg;

    perPage = 10;
    defaultParams = {
        role_name: '',
    };
    queryParams = this.defaultParams;

    @computed
    get roleOption() {
        let list = this.currentList ? toJS(this.currentList.data) : [];
        list.unshift({
            id: -1,
            name: '全部'
        })
        return list.map(item => {
            return {
                key: item.id,
                value: item.name
            };
        })
    }

    @computed
    get currentListData() {
        return toJS(this.currentList);
    }

    @computed
    get templateTreeData() {
        return toJS(this.templateTree);
    }

    @computed
    get checkedTreeNodesData() {
        return toJS(this.checkedTreeNodes);
    }


    @computed
    get isEditSubmitBtnDisabled() {
        return !this.editRoleName ||
            !this.editRoleName.trim() ||
            !this.checkedTreeNodes;
    }

    @action
    reset() {
        this.roleName = '';
        this.currentList = null;
        this.perPage = 10;
        this.templateTree = null;
        this.queryParams = this.defaultParams;
        this.resetRoleModal();
    }

    @action
    resetQueryParams() {
        this.roleName = '';
        this.queryParams = this.defaultParams;
    }

    @action
    updateQueryParams() {
        this.queryParams = {
            role_name: this.roleName.trim(),
        }
    }

    @action
    resetRoleModal() {
        this.editRoleId = null;
        this.editRoleName = null;
        this.editRoleDescription = null;
        this.checkedTreeNodes = null;
        this.defaultMenus = null;
        this.isEditSuccess = false;
        this.errMsg = {
            editRoleName: '',
            editRoleDescription: '',
        };
    }

    @action
    openRoleModal(data) {
        if (!this.templateTree) {
            this.fetchTemplateTree();
        }
        if (data) {
            this.editRoleId = data.id;
            this.editRoleName = data.name;
            this.editRoleDescription = data.description;
            this.openModal = 2;
            this.fetchRoleDetail();
        } else {
            this.openModal = 1;
        }
    }

    @action
    closeRoleModal() {
        this.openModal = null;
        this.resetRoleModal();
    }

    @action
    setCheckedTreeNodes() {
        const tree = this.templateTreeData;
        const defaultMenus = this.defaultMenus;
        if (!tree || tree.length === 0 || !defaultMenus || defaultMenus.length === 0) {
            return;
        }
        const {
            menus,
            modules
        } = getLastChildrenKeys(defaultMenus);
        this.checkedTreeNodes = [
            ...menus,
            ...modules
        ];
    }

    @action
    async fetchRoleDetail() {
        const res = await this.get(`/auth/roles/${this.editRoleId}/detail`, null, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            if (res.code === '0000') {
                const data = res.data;
                this.editRoleName = data.name;
                this.editRoleDescription = data.description;
                this.defaultMenus = data.menus;
                this.setCheckedTreeNodes();
            }
        });
    }

    @action
    async fetchTemplateTree() {
        const res = await this.get('/auth/templete-tree', null, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.templateTree = res.data;
            } else {
                this.templateTree = null;
            }
            this.setCheckedTreeNodes();
        });
    }

    @action
    async fetchListData(page) {
        const res = await this.get('/auth/roles', {
            ...this.queryParams,
            page: page || 1,

            per_page: this.perPage
        }, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.currentList = res.data;
            } else {
                this.currentList = null;
            }
        });
    }

    @action
    async editSubmit() {
        const openModal = this.openModal;
        this.globalErrMsg = '';
        const {
            menus,
            modules
        } = getAllIdsByChildrenKeys(this.templateTreeData, [...this.checkedTreeNodesData]);
        let url, data;
        data = {
            name: this.editRoleName.trim(),
            description: this.editRoleDescription.trim(),
            menus: menus,
            modules: modules,
        }
        if (openModal === 1) {
            url = '/auth/roles/add';
        } else {
            url = `/auth/roles/${this.editRoleId}/edit`;
        }
        const res = await this.post(url, data, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isEditSuccess = true;
            } else if (code === '1201') {
                this.errMsg.editRoleName = '角色名称已存在，请重新填写角色名称';
            } else {
                this.globalErrMsg = `${openModal === 1 ? '新增' : '编辑'}角色失败，请重试`;
            }
        });
    }
}

// 根据提供的moji
function getAllIdsByChildrenKeys(data, keys) {
    if (!data || !keys || data.length < 1 || keys.length < 1) {
        return null;
    }

    let result = {
        menus: [],
        modules: []
    };
    for (let i = 0, len = data.length; i < len; i++) {
        const item = data[i];
        const idxMenu = keys.indexOf('menu-' + item.id);
        const idxModule = keys.indexOf('module-' + item.id);
        if (item.menus && item.menus.length) {
            const {
                menus,
                modules
            } = getAllIdsByChildrenKeys(item.menus, keys);
            if (menus.length || modules.length) {
                menus.push(item.id);
                result.menus = result.menus.concat(menus);
                result.modules = result.modules.concat(modules);
            }
        } else if (item.modules && item.modules.length) {
            const {
                modules
            } = getAllIdsByChildrenKeys(item.modules, keys);
            if (modules.length) {
                result.menus.push(item.id);
                result.modules = result.modules.concat(modules);
            }
        } else {
            if (idxMenu !== -1 || idxModule !== -1) {
                if ('url' in item) {
                    // 这是菜单
                    result.menus.push(item.id);
                } else {
                    // 这是功能
                    result.modules.push(item.id);

                }
            }
        }
        if (idxMenu !== -1 || idxModule !== -1) {
            keys.splice(idxMenu !== -1 ? idxMenu : idxModule, 1);
        }
        if (keys.length === 0) {
            return result;
        }
    }
    return result;
}

function getLastChildrenKeys(data) {
    let menus = [];
    let modules = [];
    data && data.length && data.forEach(item => {
        if (!item.menus || !item.menus.length) {
            if (item.modules && item.modules.length) {
                item.modules.forEach(itm => modules.push(`module-${itm.id}`));
            } else {
                menus.push(`menu-${item.id}`);
            }
        } else {
            const result = getLastChildrenKeys(item.menus);
            menus = menus.concat(result.menus);
            modules = modules.concat(result.modules);
        }
    });
    return {
        menus,
        modules
    }
}

export default new Store();